#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libmscommon/mscommon.h>
#include <libmscommon/msstring.h>
#include <libmslog/mslog.h>
#include "mpeg/mpegts.h"
#include "msbitStream.h"


#define FLAG "bitStream"

#define REGISTER_RESOLVER(x) { \
    extern AVParser ffurl_##x##_parser; \
    extern int ffurl_register_resolver(AVParser *, int ); \
    ffurl_register_resolver(&ffurl_##x##_parser, sizeof(AVParser)); \
    ms_verbose("*  %s" ,ffurl_##x##_parser.name); }

static AVParser *first_parser=ms_null;

int ffurl_register_resolver(AVParser *table, int size)
{
	AVParser **p;
	if (size < sizeof(AVParser)) {
		AVParser* temp = ms_malloc(sizeof(AVParser),"AVParser");
		memcpy(temp, table, size);
		table = temp;
	}
	p = &first_parser;
		while (*p != ms_null){
		p = (AVParser **)&(*p)->next;
	}
	*p = table;
	table->next = ms_null;
	return 0;
}
	
void * ffurl_match_resolver(const char *name)
{
	AVParser **p= &first_parser;
		if(ms_null==name){
			ms_error( "Param error");
			return ms_null ;
		}
		while (*p != ms_null){
		if( ms_strncmp_saeq(name, (*p)->name)){
			break;
		}
		p =(AVParser **) &(*p)->next;
	}
	return (void *)*p ;
}

void bitStream_register_parser(void)
{
#ifdef CONFIG_RESOLVER
	ms_verbose("===RESOLVER *  Table===");
	#ifdef CONFIG_RESOLVER_MPEGTS
	REGISTER_RESOLVER(mpegts);
	#else
		ms_more("*  no-mpegts"); 	
	#endif
	#ifdef CONFIG_RESOLVER_FLV
		ms_verbose("*  flvparser"); 
	#else
		ms_more("*  no-flvparser"); 	
	#endif
	#ifdef CONFIG_RESOLVER_MP3
		ms_verbose("*  mp3parser"); 
	#else
		ms_verbose("*  no-mp3parser"); 
	#endif
	ms_verbose("=========================");	
#endif
}
ms_void msbitStream_api_info(ms_string ms_out pbuf)
{
#if defined OS_LINUX_SOC  
	#if defined OS_PLATFORM_ARM64  
		strcat(pbuf, "linux_aarch64");
	#elif defined OS_PLATFORM_ARMV7L
		strcat(pbuf, "linux_armv7l");
	#else
		strcat(pbuf, "linux_soc");
	#endif
#else
	#if defined OS_PLATFORM_ARM64  
		strcat(pbuf, "unlinux_aarch64");
	#elif defined OS_PLATFORM_ARMV7L
		strcat(pbuf, "unlinux_armv7l");
	#else
		strcat(pbuf, "unlinux_soc");
	#endif
#endif
	#ifdef CONFIG_RESOLVER
	#ifdef CONFIG_RESOLVER_MPEGTS
		strcat(pbuf, "|mpegts_parser");	
	#endif
	#ifdef CONFIG_RESOLVER_FLV
		strcat(pbuf, "|flv_parser");	
	#endif
	#ifdef CONFIG_RESOLVER_MP3
		strcat(pbuf, "|mp3_parser");
	#endif
#endif
}
ms_void msbitStream_api_init(ms_void)
{
	mpegts_api_init();
}
ms_string msbitStream_api_version(ms_void)
{
	return "01.00.47";
}

